package com.erdos.common.util.log;

//import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.LoggingEvent;

import com.erdos.common.service.AppServiceHelper;


public class JDBCPoolAppender extends JDBCAppender {

	DataSource ds = null;

//	@Override
//	protected void execute(String sql) {
//		if(ds==null){
//			ds = (DataSource) AppServiceHelper.findBean("dataSource");
//		}
//		Connection con = null;
//		Statement stmt = null;
//		try {
//			con = ds.getConnection();
//			if (con == null)
//				return;
//			// System.out.println(sql + ":" + this.connection);
//			stmt = con.createStatement();
//			stmt.executeUpdate(sql);
//		} catch (SQLException e) {
//
//		} finally {
//			try {
//				if (stmt != null)
//					stmt.close();
//				if (con != null)
//					con.close();
//			} catch (SQLException e) {
//				e.printStackTrace();
//			}
//		}
//	}
	
	@Override
	protected void execute(String sql) {
		Statement stmt = null;
		try {
			if(connection==null){
				ds = (DataSource) AppServiceHelper.findBean("dataSource");
				connection=ds.getConnection();
			}
			if (connection == null)
				return;
			// System.out.println(sql + ":" + this.connection);
			stmt = connection.createStatement();
			stmt.executeUpdate(sql);
		} catch (SQLException e) {

		} finally {
			try {
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public String getLogStatement(LoggingEvent event) {
		StringBuffer sbuf = new StringBuffer();
		sbuf.append(layout.format(event));
		if (layout.ignoresThrowable()) {
			sbuf.delete(sbuf.length() - 2, sbuf.length());
			String[] s = event.getThrowableStrRep();
			if (s != null) {
				for (int j = 0; j < 10; j++) {
					sbuf.append("\r\n");
					sbuf.append(s[j]);
				}
			}
			sbuf.append("')");
		}
		return sbuf.toString();
	}

}
